package com.cloudcc.mobile.view.dynamic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.cloudcc.cloudframe.bus.BaseEvent;
import com.cloudcc.cloudframe.bus.DynamicEventList.SendDynamicEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.net.IServer;
import com.cloudcc.cloudframe.util.PackageUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OnAddImageListener;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OnShowImageListener;
import com.cloudcc.mobile.adapter.AddmicroPostGridviewAdapter.OndeleteListener;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.addmicropost.Option;
import com.cloudcc.mobile.event.isleft;
import com.cloudcc.mobile.event.isshow;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.AtContaxtActivity;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.activity.GroupActivity;
import com.cloudcc.mobile.view.activity.SelectPhotoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.wel.WelcomeActivity;
import com.cloudcc.mobile.weight.GridViewForListView;
import com.litesuits.android.log.Log;
import com.mypage.utils.AnimViewUtils;
import com.mypage.utils.NetStateUtils;
import com.mypage.utils.SaveTemporaryData;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static com.cloudcc.mobile.R.id.addView;


/**
 * 发布微帖
 *
 * @author sevenf
 */

public class SendTimeLineActivity extends BaseActivity implements
        OnClickListener, IEventLife, View.OnFocusChangeListener {
    @Bind(R.id.imgDeletes)
    ImageView imgDeletes;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    public static final String KEY_PHOTO_PATH = "photo_path";
    private static final int SELECT_PHOTO = 5000;
    private static final int TAKE_PHOTO = 5001;
    private static final int ADDMICROPOST_ACTIVITY_AT = 7001;
    private static final int INTENT_QX = 7007;

    @Bind(R.id.title)
    TextView tvUserName;
    @Bind(R.id.tv1)
    TextView tvAddress;
    @Bind(R.id.dynamic_content)
    EditText etDynamicContent;
    @Bind(R.id.dynamic_toupiao_ed)
    EditText dynamic_toupiao_ed;
    @Bind(R.id.quanxian)
    TextView quanxian;
    @Bind(R.id.dingwei)
    RelativeLayout dingwei;
    @Bind(R.id.tableRow1)
    LinearLayout tableRow1;
    @Bind(R.id.tableRow2)
    LinearLayout tableRow2;
    @Bind(R.id.paizhao)
    ImageView paizhao;

    @Bind(R.id.wenjian)
    ImageView wenjian;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;
    @Bind(R.id.xiaolian)
    ImageView xiaolian;

    @Bind(R.id.tianjia)
    ImageView tianjia;
    @Bind(R.id.back)
    ImageView dyback;
    @Bind(R.id.send)
    ImageView dysend;

    /**
     * 图片 列表 容器
     */
    @Bind(R.id.gridview1)
    GridViewForListView containerGridViewPhoto;
    /**
     * 连接的容器
     */
    @Bind(R.id.newlinked)
    LinearLayout containerLink;

    /**
     * 连接 中 连接的url
     */
    @Bind(R.id.linkedurl)
    EditText etLinkUrl;

    /**
     * 连接 中 网址详情
     */
    @Bind(R.id.ms)
    EditText etLinkUrlDesc;
    /**
     * 投票的容器
     */
    @Bind(R.id.toupiao)
    LinearLayout containerVote;

    @Bind(R.id.toupiao_sc)
    LinearLayout toupiao_sc;
    /**
     * 投票 添加 选项
     */
    @Bind(addView)
    ImageView voteAddOps;

    /**
     * 投票的选项布局 容器
     */
    @Bind(R.id.buju)
    LinearLayout voteOptionLayout;
    private RelativeLayout topLayoutBackg;
    private TextView toastHintContent;
    private DynamicType mDynamicType = DynamicType.COMMON;
    /**
     * 当前的 图片数量
     */
    private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();

    private boolean dwflag = false;

    @Bind(R.id.kongbai)
    TextView kongbai;

    @Bind(R.id.oneedittext1)
    EditText oneedittext1;
    @Bind(R.id.oneedittext2)
    EditText oneedittext2;

    @Bind(R.id.huoqu)
    Button huoqu;

    private ArrayList<View> editViews = new ArrayList<View>();// 动态的布局
    private AddmicroPostGridviewAdapter adapter;

    private String imagename;
    private Uri photoUri;
    public static String picPath = null;

    private String group_name, group_id;
    private String relevantId = "";

    private DynamicControl dynamicControl = new DynamicControl();
    //滑动监听
    private float mPosX, mPosY, mCurPosX, mCurPosY;
    private static final int FLING_MIN_DISTANCE = 20;// 移动最小距离
    private static final int FLING_MIN_VELOCITY = 200;// 移动最大速度

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        junpGetData();
        toastHintContent = (TextView) findViewById(R.id.toastHintContent);
        topLayoutBackg = (RelativeLayout) findViewById(R.id.topLayoutBackg);
//		initViewa();
        // 检测是不是正在运行状态
        boolean running = PackageUtils.isRunning(mContext,
                mContext.getPackageName());
        if (!running) {
            AppContext.isFenXiang = true;
            Intent intent = new Intent(mContext, WelcomeActivity.class);
            startActivity(intent);
            this.finish();
        }
        register();
        setupView();
        initLocation();
        initclick();

    }
    public void junpGetData() {
        SaveTemporaryData.DraftBoxPosition = getIntent().getStringExtra("POSITION");
        String content = getIntent().getStringExtra("content");
        etDynamicContent.setText(content);
        if (content==""||content==null||content.length()==0){
            dysend.setEnabled(false);
            dysend.setImageResource(R.drawable.yuntie_fasong_false);
        }else {
            dysend.setEnabled(true);
            dysend.setImageResource(R.drawable.yuntie_send_true);
        }


    }


    //上滑收起软键盘
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;
    isshow issh = new isshow();
    isleft isle = new isleft();

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // 当手指按下的时候
//			Log.d("zuobiao", "(" + x1 + "," + y1 + ")(" + x2 + "," + y2 + ")");
            x1 = event.getX();
            y1 = event.getY();
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            // 当手指离开的时候
            x2 = event.getX();
            y2 = event.getY();
            Log.d("zuobiao", "(" + x1 + "," + y1 + ")(" + x2 + "," + y2 + ")");
            if ((y1 - y2 > 200)) {
                Log.d("zuobiao", "shang");
                issh.isshow = true;
                InputMethodManager imm1 = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm1.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);//从控件所在的窗口中隐藏
                EventBus.getDefault().post(issh);
            } else if ((y2 - y1 > 200)) {
                issh.isshow = false;
                EventBus.getDefault().post(issh);
            }

        }
        return super.dispatchTouchEvent(event);
    }

    private void initclick() {
        //焦点监听
        oneedittext1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tableRow1.setBackgroundResource(R.drawable.dy_bg_true);
                } else {
                    tableRow1.setBackgroundResource(R.drawable.dy_bg_false);
                }
            }
        });
        oneedittext2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tableRow2.setBackgroundResource(R.drawable.dy_bg_true);
                } else {
                    tableRow2.setBackgroundResource(R.drawable.dy_bg_false);
                }
            }
        });

        //输入状态监听
//		dynamic_toupiao_ed.length()!= 0&&
        dynamic_toupiao_ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (dynamic_toupiao_ed.length() != 0 && oneedittext1.length() != 0 && oneedittext2.length() != 0) {
                    dysend.setEnabled(true);
                    dysend.setImageResource(R.drawable.yuntie_send_true);
                } else {
                    dysend.setEnabled(false);
                    dysend.setImageResource(R.drawable.yuntie_fasong_false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        oneedittext1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (oneedittext1.length() >= 50) {
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                    if ("en".equals(mEns)) {
                        toastHintContent.setText("The number of fields exceeds the limit");
                    } else {
                        toastHintContent.setText("字段数超出限制");
                    }
                    new AnimViewUtils().appearToast(layoutTop);
                    new AnimViewUtils().setHintToast(layoutTop);
                }
                if (dynamic_toupiao_ed.length() != 0 && oneedittext1.length() != 0 && oneedittext2.length() != 0) {
                    dysend.setEnabled(true);
                    dysend.setImageResource(R.drawable.yuntie_send_true);
                } else {
                    dysend.setEnabled(false);
                    dysend.setImageResource(R.drawable.yuntie_fasong_false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        oneedittext2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (oneedittext2.length() >= 50) {
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                    if ("en".equals(mEns)) {
                        toastHintContent.setText("The number of fields exceeds the limit");
                    } else {
                        toastHintContent.setText("字段数超出限制");
                    }
                    new AnimViewUtils().appearToast(layoutTop);
                    new AnimViewUtils().setHintToast(layoutTop);
                }
                if (dynamic_toupiao_ed.length() != 0 && oneedittext1.length() != 0 && oneedittext2.length() != 0) {
                    dysend.setEnabled(true);
                    dysend.setImageResource(R.drawable.yuntie_send_true);
                } else {
                    dysend.setEnabled(false);
                    dysend.setImageResource(R.drawable.yuntie_fasong_false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etDynamicContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s==null||s.length()==0){
                    dysend.setEnabled(false);
                    dysend.setImageResource(R.drawable.yuntie_fasong_false);
                }else{
                    dysend.setEnabled(true);
                    dysend.setImageResource(R.drawable.yuntie_send_true);
                }

            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.imgDeletes)
    public void onClick() {
        layoutTop.setVisibility(View.GONE);
    }

    class EdittextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() >= 50) {
//				Toast.makeText(SendTimeLineActivity.this, "输入字数不能超过50个字", Toast.LENGTH_SHORT).show();
                topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                if ("en".equals(mEns)) {
                    toastHintContent.setText("The number of fields exceeds the limit");
                } else {
                    toastHintContent.setText("字段数超出限制");
                }
                new AnimViewUtils().appearToast(layoutTop);
                new AnimViewUtils().setHintToast(layoutTop);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }

//一下是隐藏按钮
//	private void initViewa() {
//		// TODO Auto-generated method stub
//		String mStrs = getIntent().getStringExtra("xianshi");
////		if ("a".equals(mStrs)) {
////			paizhao.setVisibility(View.VISIBLE);
////		
////			
////		wenjian.setVisibility(View.VISIBLE);
////			
////			
////		
////		 xiaolian.setVisibility(View.VISIBLE);
////			
////			
////			 tianjia.setVisibility(View.VISIBLE);
////			 
////			 tvAddress.setVisibility(View.VISIBLE);
////			 quanxian.setVisibility(View.VISIBLE);
////		}else{
//			quanxian.setVisibility(View.INVISIBLE);
//			tvAddress.setVisibility(View.INVISIBLE);
//			paizhao.setVisibility(View.INVISIBLE);
//			
//			
//			wenjian.setVisibility(View.INVISIBLE);
//				
//				
//			
//			 xiaolian.setVisibility(View.INVISIBLE);
//				
//				
//				 tianjia.setVisibility(View.INVISIBLE);
//		}
//	}

    private void setupView() {
        relevantId = getIntent().getStringExtra("relevantId");
        tvUserName.setText(UserManager.getManager().getUser().userName);
        if ("en".equals(mEns)) {
            tvAddress.setText("Is positioning......");
        } else {
            tvAddress.setText("正在定位......");
        }

        adapter = new AddmicroPostGridviewAdapter(this, imageArray);
        containerGridViewPhoto.setAdapter(adapter);
        setAdapterListener();
    }

    private void initLocation() {
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }

    private void refreshType() {

        if (containerGridViewPhoto.getVisibility() == View.VISIBLE
                && imageArray.size() > 0) {// 图片
            mDynamicType = DynamicType.PHOTO;
            return;
        }
        if (containerVote.getVisibility() == View.VISIBLE) {
            mDynamicType = DynamicType.VOTE;
            return;
        }
        if (containerLink.getVisibility() == View.VISIBLE) {
            mDynamicType = DynamicType.LINK;
            return;
        }
        mDynamicType = DynamicType.COMMON;

    }

    /**
     * 发布 投票 动态
     */
    private void sendVoteDynamic() {

        AddMicroPostV addMicroPostV = new AddMicroPostV();
        if (!dwflag && null != lastDBLocation) {
            addMicroPostV.setLatitude(lastDBLocation.getLatitude());
            addMicroPostV.setLongitude(lastDBLocation.getLongitude());
            addMicroPostV.setAddress(LocationManager.getDetailAddr(
                    lastDBLocation, false));
        }
        if (relevantId != null) {
            addMicroPostV.setTargetType("record");
            addMicroPostV.setTargetId(relevantId);
        }
        if (group_id != null && !group_id.equals("")) {
            addMicroPostV.setTargetType("group");
            addMicroPostV.setTargetId(group_id);
        }
        ArrayList<Option> options = new ArrayList<Option>();


        String op1 = oneedittext1.getText().toString().trim();
        String op2 = oneedittext2.getText().toString().trim();
        String voteTitle = dynamic_toupiao_ed.getText().toString().trim();// 投票主题

        if (StringUtils.isBlank(voteTitle)) {
            if ("en".equals(mEns)) {
                Tools.showInfo(this, "Please fill in the ballot");
            } else {
                Tools.showInfo(this, "请填写投票主题");
            }

            return;
        }
        if (StringUtils.isBlank(op1) || StringUtils.isBlank(op2)) {
            if ("en".equals(mEns)) {
                Tools.showInfo(this, "Please fill in at least 2 options");
            } else {
                Tools.showInfo(this, "请至少填写2个选项");
            }

            return;
        }
        Option option1 = new Option();
        option1.setOption(op1);
        Option option2 = new Option();
        option2.setOption(op2);
        options.add(option1);
        options.add(option2);

        if (editViews.size() > 0) {

            for (int i = 0; i < editViews.size(); i++) {
                EditText text1 = (EditText) editViews.get(i).findViewById(
                        R.id.xged);

                String xx = text1.getText().toString().trim();

                if (!Tools.isNull(xx)) {
                    Option oo = new Option();
                    oo.setOption(text1.getText().toString().trim());
                    options.add(oo);
                }
            }
        }
        addMicroPostV.setBody(voteTitle);
        String aaaa = Json.toJson(options);
        addMicroPostV.setPollOptions(aaaa);
        onSend(addMicroPostV, IServer.SERVICENAME_VOTE);

    }

    /**
     * 发布连接动态
     */
    private void sendLinkDynamic() {
        AddMicroPostL addMicroPostL = new AddMicroPostL();
        if (!dwflag && null != lastDBLocation) {
            addMicroPostL.setLatitude(lastDBLocation.getLatitude());
            addMicroPostL.setLongitude(lastDBLocation.getLongitude());
            addMicroPostL.setAddress(LocationManager.getDetailAddr(
                    lastDBLocation, false));
        }
        if (relevantId != null) {
            addMicroPostL.setTargetType("record");
            addMicroPostL.setTargetId(relevantId);
        }
        if (group_id != null && !group_id.equals("")) {
            addMicroPostL.setTargetType("group");
            addMicroPostL.setTargetId(group_id);
        }
        addMicroPostL.setBody(etDynamicContent.getText().toString().trim());
        String name = etLinkUrlDesc.getText().toString().trim();
        String url = etLinkUrl.getText().toString().trim();
        if(url.contains("http://")){
            url = url.substring(7,url.length());
        }

        if (StringUtils.isBlank(url)) {
            if ("en".equals(mEns)) {
                Tools.showInfo(this, "Please enter URL");
            } else {
                Tools.showInfo(this, "请输入网址");
            }

            return;
        }
        if (url.length() < 8) {
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Web site written unqualified");
            } else {
                Tools.showInfo(mContext, "网址写法不合格");
            }

            return;
        }
        String h = url.substring(0, 7);
        if (!h.equals("http://")) {
            addMicroPostL.setLinkValue("http://" + url);
        } else {
            addMicroPostL.setLinkValue(url);
        }
        addMicroPostL.setLinkName(name);
        onSend(addMicroPostL, IServer.SERVICENAME_LINK);

    }

    /**
     * 发送图片
     */
    private void sendPhotoDynamic() {
        AddMicroPostDMany addMicroPostDMany = new AddMicroPostDMany();
        if (!dwflag && null != lastDBLocation) {
            addMicroPostDMany.setLatitude(lastDBLocation.getLatitude());
            addMicroPostDMany.setLongitude(lastDBLocation.getLongitude());
            addMicroPostDMany.setAddress(LocationManager.getDetailAddr(
                    lastDBLocation, false));
            Log.d("location", addMicroPostDMany.latitude + "::"
                    + addMicroPostDMany.longitude + "::"
                    + addMicroPostDMany.address);
        }
        if (relevantId != null) {
            addMicroPostDMany.setTargetType("record");
            addMicroPostDMany.setTargetId(relevantId);
            Log.d("location", "TargetId:" + addMicroPostDMany.targetId);

        }
        if (group_id != null && !group_id.equals("")) {
            addMicroPostDMany.setTargetType("group");
            addMicroPostDMany.setTargetId(group_id);
            Log.d("location", "group_id:" + addMicroPostDMany.targetId);
        }
        addMicroPostDMany.setBody(etDynamicContent.getText().toString().trim());
        if ("en".equals(mEns)) {
            showWainting("Uploading image...");
        } else {
            showWainting("正在上传图片...");
        }


        Log.d("location", "body::" + addMicroPostDMany.body);
        Log.d("imageinfo", "image::" + imageArray.get(0).getImagePath());

        dynamicControl.sendPhotoDynamic(imageArray, addMicroPostDMany);

    }

    /**
     * 发送普通的动态
     */
    private void sendCommonDynamic() {
        AddMicroPostF addMicroPostF = new AddMicroPostF();
        if (!dwflag && null != lastDBLocation) {
            addMicroPostF.setLatitude(lastDBLocation.getLatitude());
            addMicroPostF.setLongitude(lastDBLocation.getLongitude());
            addMicroPostF.setAddress(LocationManager.getDetailAddr(
                    lastDBLocation, false));
        }
        if (relevantId != null) {
            addMicroPostF.setTargetType("record");
            addMicroPostF.setTargetId(relevantId);
        }
        if (group_id != null && !group_id.equals("")) {
            addMicroPostF.setTargetType("group");
            addMicroPostF.setTargetId(group_id);
        }
        String body = etDynamicContent.getText().toString().trim();

        if (StringUtils.isBlank(body)) {
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Please enter the post content");
            } else {
                Tools.showInfo(mContext, "请输入帖子内容");
            }

            return;
        }
        addMicroPostF.setBody(body);

        onSend(addMicroPostF, IServer.SERVICENAME_FOLLEW);

    }

    @OnClick(R.id.send)
    public void clickSend() {
        refreshType();
        RunTimeManager.getInstance().setIsRefreshx(true);
        if (mDynamicType == DynamicType.COMMON) {
            sendCommonDynamic();
            return;
        }
        if (mDynamicType == DynamicType.PHOTO) {
            sendPhotoDynamic();
            return;
        }
        if (mDynamicType == DynamicType.LINK) {
            sendLinkDynamic();
            return;
        }
        if (mDynamicType == DynamicType.VOTE) {
            sendVoteDynamic();
            return;
        }
    }

    public void sendDeleteCaoGaoItem() {
        if (NetStateUtils.isNetworkConnected(this)){
            SaveTemporaryData.mSmart = "deleteItems";
        }else{
            SaveTemporaryData.mSmart = "noconnect";
        }

    }

    private void onSend(Object obj, String ServiceName) {
        if ("en".equals(mEns)) {
            showWainting("Publishing micro paste...");
        } else {
            showWainting("正在发布微贴...");
        }

        dynamicControl.sendCommonDynamic(obj, ServiceName);
    }

    // GridView监听
    private void setAdapterListener() {
        containerGridViewPhoto.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                adapter.setDeleteModel(false);
                return true;
            }
        });
        adapter.setOnAddImageListener(new OnAddImageListener() {
            @Override
            public void add() {
                AppContext.isSelectedNum = imageArray.size();
                Intent intent = new Intent(mContext, SelectPhotoActivity.class);
                startActivityForResult(intent, SELECT_PHOTO);
            }
        });
        adapter.setOndeleteListener(new OndeleteListener() {
            @Override
            public void delete(int posion) {
                imageArray.remove(posion);
                if (imageArray.size() == 0) {
                    adapter.setDeleteModel(false);
                } else {
                    adapter.notifyDataSetChanged();
                }
            }
        });
        adapter.setOnShowImageListener(new OnShowImageListener() {
            @Override
            public void show(int posion) {
                File file = new File(imageArray.get(posion).getImagePath());
                Intent it = new Intent(Intent.ACTION_VIEW);
                Uri mUri = Uri.parse("file://" + file.getPath());
                it.setDataAndType(mUri, "image/*");
                startActivity(it);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_del:
                View view = (View) v.getTag();
                removeView(view);
                break;
        }
    }

    int i = 0;

    @OnClick(R.id.huoqu)
    public void clickHuoQu() {
        for (int i = 0; i < editViews.size(); i++) {
            EditText text1 = (EditText) editViews.get(i)
                    .findViewById(R.id.xged);
            System.out.println(text1.getText());
        }
    }

    /**
     * 点击投票的时候 的 添加选项
     */
    @OnClick(addView)
    public void clickVoteAddOps() {
        if (mDynamicType != DynamicType.VOTE) {
            refreshLayout();
            return;
        }


        String[] tv = {"三", "四", "五", "六", "七", "八", "九", "十", "", "", ""};
        String[] etv = {"3", "4", "5", "6", "7", "8", "9", "10", "", "", ""};
        if (editViews.size() < 8) {
            View view = LayoutInflater.from(getBaseContext()).inflate(
                    R.layout.toupiao_item, null);
            Button btnDel = (Button) view.findViewById(R.id.bt_del);// 删除
            EditText text = (EditText) view.findViewById(R.id.xged);
//            TextView xxtv = (TextView) view.findViewById(R.id.xgtv);
            text.addTextChangedListener(new EdittextChange());
            if ("en".equals(mEns)) {
                text.setHint("Option" + etv[i] + ":");

            } else {
                text.setHint("选项" + tv[i] + ":");
            }

            i++;
            // 输入框

//			btnDel.setTag(view);
//			btnDel.setOnClickListener(this);
            text.setTag(view);
            text.setOnFocusChangeListener(this);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            voteOptionLayout.addView(view, params);

            editViews.add(view);
            //输入状态监听
            if (editViews.size() == 8) {
                voteAddOps.setVisibility(View.GONE);
            }

        } else {
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Up to 10 voting options");
            } else {
                Tools.showInfo(mContext, "亲~ 最多可有10个投票选项");
            }

        }
    }


    /**
     * 选择 帖子的类型
     */
    @OnClick(R.id.quanxian)
    public void clickLimit() {
        Intent ia = new Intent(SendTimeLineActivity.this, GroupActivity.class);
        ia.putExtra("quanxian", quanxian.getText().toString());
        startActivityForResult(ia, INTENT_QX);
    }

    @OnClick(R.id.tv1)
    public void clickLocation() {
        if (dwflag) {
            if ("en".equals(mEns)) {
                tvAddress.setText(null == lastDBLocation ? "Is positioning..."
                        : LocationManager.getDetailAddr(lastDBLocation, false));
            } else {
                tvAddress.setText(null == lastDBLocation ? "正在定位..."
                        : LocationManager.getDetailAddr(lastDBLocation, false));
            }

            dwflag = false;
        } else {
            if ("en".equals(mEns)) {
                tvAddress.setText("Insert position");
            } else {
                tvAddress.setText("插入位置");
            }

            dwflag = true;
        }
    }

    /**
     * 点击投票
     */
    @OnClick(R.id.tianjia)
    public void clickVote() {
        mDynamicType = containerVote.getVisibility() == View.VISIBLE ? DynamicType.COMMON
                : DynamicType.VOTE;
//		mDynamicType = containerVote.getVisibility() == View.VISIBLE ? DynamicType.COMMON
//				: DynamicType.VOTE;
        dysend.setEnabled(false);
        if (dynamic_toupiao_ed.getVisibility() == View.VISIBLE) {

            dynamic_toupiao_ed.setVisibility(View.GONE);
            etDynamicContent.setVisibility(View.VISIBLE);
            dysend.setEnabled(false);
            dysend.setImageResource(R.drawable.yuntie_fasong_false);

        } else {
            dynamic_toupiao_ed.setVisibility(View.VISIBLE);
            etDynamicContent.setVisibility(View.GONE);
        }


        refreshLayout();
    }

    /**
     * 点击连接
     */
    @OnClick(R.id.xiaolian)
    public void clickLink() {

        mDynamicType = containerLink.getVisibility() == View.VISIBLE ? DynamicType.COMMON
                : DynamicType.LINK;
        dynamic_toupiao_ed.setVisibility(View.GONE);
        etDynamicContent.setVisibility(View.VISIBLE);
        dysend.setEnabled(true);
        dysend.setImageResource(R.drawable.yuntie_send_true);
        refreshLayout();
    }

    /**
     * 点击相册
     */
    @OnClick(R.id.wenjian)
    public void clickGallery() {
        dynamic_toupiao_ed.setVisibility(View.GONE);
        etDynamicContent.setVisibility(View.VISIBLE);
//        dysend.setEnabled(true);
//        dysend.setImageResource(R.drawable.yuntie_send_true);
        Intent intent = new Intent(mContext, SelectPhotoActivity.class);
        startActivityForResult(intent, SELECT_PHOTO);
    }


    private void refreshLayout() {
        containerLink.setVisibility(View.GONE);
        kongbai.setVisibility(View.GONE);
        containerVote.setVisibility(View.GONE);
        containerGridViewPhoto.setVisibility(View.GONE);
        if (mDynamicType == DynamicType.PHOTO) {
            containerGridViewPhoto.setVisibility(View.VISIBLE);
            dingwei.setVisibility(View.VISIBLE);
            return;
        }
        // 如果不是图片的话 先清空
        imageArray.clear();
        if (mDynamicType == DynamicType.LINK) {
            containerLink.setVisibility(View.VISIBLE);
            dingwei.setVisibility(View.VISIBLE);
            return;
        }
        if (mDynamicType == DynamicType.VOTE) {
            dysend.setEnabled(false);
            dysend.setImageResource(R.drawable.yuntie_fasong_false);
            containerVote.setVisibility(View.VISIBLE);
            dingwei.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 点击相机
     */
    @OnClick(R.id.paizhao)
    public void clickCamera() {
//        dysend.setEnabled(true);
//        dysend.setImageResource(R.drawable.yuntie_send_true);
        dynamic_toupiao_ed.setVisibility(View.GONE);
        etDynamicContent.setVisibility(View.VISIBLE);
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, TAKE_PHOTO);
        } else {
            Tools.showInfo(SendTimeLineActivity.this, "请插入SD卡");
        }
    }

    private void removeView(View view) {
        voteOptionLayout.removeView(view);
        editViews.remove(view);
    }

    @OnClick(R.id.back)
    public void onClickBack() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == SELECT_PHOTO) {// 选图片
            mDynamicType = DynamicType.PHOTO;
            setPhotos();
        } else if (requestCode == TAKE_PHOTO) {// 照相
            mDynamicType = DynamicType.PHOTO;
            if (imageArray.size() + 1 > 9) {
                Tools.showInfo(mContext, "最多添加9张图片");
            } else {
                File f = new File(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo/" + imagename);
                try {
                    Uri u = Uri.parse(MediaStore.Images.Media
                            .insertImage(getContentResolver(),
                                    f.getAbsolutePath(), null, null));
                    String imageurl = getAbsoluteImagePath(u);
                    AddImageInfo imageInfo = new AddImageInfo();
                    imageInfo.setImagePath(imageurl);
                    imageArray.add(imageInfo);
                    setPhotos();
                } catch (FileNotFoundException e) {
                    Tools.handle(e);
                }
            }
        } else if (requestCode == ADDMICROPOST_ACTIVITY_AT) {// @某人
            String a = data.getStringExtra("name");
            String[] c = a.split(",");
            for (int i = 0; i < c.length; i++) {
                if (!c[i].equals("")) {

                    if (dynamic_toupiao_ed.getVisibility() == View.VISIBLE) {
                        dynamic_toupiao_ed.append(" @[" + c[i] + "]" + " ");
                    } else {
                        etDynamicContent.append(" @[" + c[i] + "]" + " ");
                    }

                }
            }
        } else if (requestCode == INTENT_QX) {// 权限返回的数据
            group_name = data.getStringExtra("groupname");
            quanxian.setText(group_name);
            group_id = data.getStringExtra("groupid");
        }
        refreshLayout();
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Tools.showInfo(mContext, "最多添加9张图片");
                    break;
                case 2:
                    adapter = new AddmicroPostGridviewAdapter(
                            SendTimeLineActivity.this, imageArray);
                    containerGridViewPhoto.setAdapter(adapter);
                    containerGridViewPhoto.setVisibility(View.VISIBLE);
                    setAdapterListener();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 设置选中的 图片
     */
    private void setPhotos() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;
        if (imageArray.size() + selectedImagePathArray.size() > 9) {
            selectedImagePathArray.clear();
            if ("en".equals(mEns)) {
                Tools.showInfo(mContext, "Add up to 9 images");
            } else {
                Tools.showInfo(mContext, "最多添加9张图片");
            }

            return;
        }
        for (String imagePath : selectedImagePathArray) {
            if (imageArray.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();
            imageInfo.setImagePath(imagePath);
            imageArray.add(imageInfo);
        }
        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
        containerGridViewPhoto.setAdapter(adapter);
        setAdapterListener();
        selectedImagePathArray.clear();
    }

    private void shareImage() {
        Bundle data = getIntent().getExtras();
        if (data != null) {
            // if (AppContext.islogining) {
            Uri imgUri = (Uri) data.getParcelable(Intent.EXTRA_STREAM);
            String urlpath = getAbsoluteImagePath(imgUri);
            AddImageInfo imageInfo = new AddImageInfo();
            imageInfo.setImagePath(urlpath);
            if (imageArray.size() != 0) {
                for (int i = 0; i < imageArray.size(); i++) {
                    if (urlpath.equals(imageArray.get(i).getImagePath())) {
                        AppContext.isFenXiang = false;
                    } else {
                        AppContext.isFenXiang = true;
                    }
                }
            } else {
                AppContext.isFenXiang = true;
            }
            if (AppContext.isFenXiang) {
                imageArray.add(imageInfo);
                adapter.changeData(imageArray);
            }
            containerGridViewPhoto.setVisibility(View.VISIBLE);
            dingwei.setVisibility(View.VISIBLE);
            AppContext.isBundle = null;
            // } else {
            // AppContext.isBundle = data;
            // Intent intent = new Intent(mContext, WelcomeActivity.class);
            // startActivity(intent);
            // AppContext.isFenXiang = true;
            // finish();
            // }
        } else {
            if (AppContext.isBundle != null) {
                Uri imgUri = (Uri) AppContext.isBundle
                        .getParcelable(Intent.EXTRA_STREAM);
                String urlpath = getAbsoluteImagePath(imgUri);
                AddImageInfo imageInfo = new AddImageInfo();
                imageInfo.setImagePath(urlpath);
                if (AppContext.isFenXiang) {
                    imageArray.add(imageInfo);
                    adapter.changeData(imageArray);
                }
                containerGridViewPhoto.setVisibility(View.VISIBLE);
                dingwei.setVisibility(View.VISIBLE);
                AppContext.isBundle = null;
                urlpath = "";
            }
        }
    }

    @OnClick(R.id.tingxingmouren)
    public void clickAiTe() {
        dysend.setEnabled(true);
        dysend.setImageResource(R.drawable.yuntie_send_true);
        Intent intent = new Intent(SendTimeLineActivity.this,
                AtContaxtActivity.class);
        startActivityForResult(intent, ADDMICROPOST_ACTIVITY_AT);
    }

    public void onEventMainThread(SendDynamicEvent event) {
        dismissWainting();
        if (event.isError()) {
            if (event.getStatusCode() == BaseEvent.SC_LOGIN_INVAILED) {// 登录失效
                Intent intent = new Intent(mContext, BindActivity.class);
                mContext.startActivity(intent);
            } else if (event.getStatusCode() == BaseEvent.NET_NO_NETWORK) {// 没有网络
                sendDeleteCaoGaoItem();
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "No network...");
                } else {
                    Tools.showInfo(mContext, "暂无网络...");
                }

            } else {
                if ("en".equals(mEns)) {
                    Tools.showInfo(mContext, "Release micro paste failed, has been saved to the draft box");
                } else {
                    Tools.showInfo(mContext, "发布微贴失败,已经保存到草稿箱");
                }
                SaveTemporaryData.mSmart = "deleteItems";
                // 刷新
                Intent caogao = new Intent(AppContext.CAOGAO_NUM);
                mContext.sendBroadcast(caogao);
                finish();
            }
            return;
        }
        EventEngine.post(new RefreshDynamicListEvent());
        SaveTemporaryData.mSmart = "deleteItems";
        finish();

    }

    @Override
    protected void onStop() {

        try {
            AppContext.isFenXiang = false;
        } catch (Exception e) {
            Tools.handle(e);
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        try {
            shareImage();
        } catch (Exception e) {
            Tools.handle(e);
        }
        super.onResume();
    }

    public String getAbsoluteImagePath(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    @Override
    protected void onDestroy() {
        unRegister();
        LocationManager.getInstance().unregisterlistener(mListener);
        try {
            AppContext.isSelectedNum = 0;
            AppContext.isFenXiang = true;
        } catch (Exception e) {
            Tools.handle(e);
        }
        super.onDestroy();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        View view = (View) v.getTag();
//        RelativeLayout re_ed_toupiao = (RelativeLayout)view.findViewById(R.id.re_ed_toupiao);
//        EditText xg = (RelativeLayout)view.findViewById(re_ed_toupiao);
        EditText xged = (EditText) view.findViewById(R.id.xged);

        switch (v.getId()) {
            case R.id.xged:
                if (hasFocus) {

                    xged.setBackgroundResource(R.drawable.dy_bg_true);

                    break;
                } else {
                    xged.setBackgroundResource(R.drawable.dy_bg_false);
                    break;
                }
        }

    }


    private enum DynamicType {
        COMMON, // 普通
        PHOTO, // 图片
        LINK, // 连接
        VOTE, // 投票
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_sendtimeling;
    }

    @Override
    public void register() {
        EventEngine.register(this);

    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    private BDLocation lastDBLocation;
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location
                    && location.getLocType() != BDLocation.TypeServerError) {
                if("4.9E-324".equals(String.valueOf(location.getLatitude()))){
                    if ("en".equals(mEns)) {
                        showToast("The location failed. Check that the location permission is open");
                    } else {
                        showToast("定位失败，请查看位置权限是否打开");
                    }
                   LocationManager.getInstance().stopRequestLocal();
                }
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                refreshTvAddress();
            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Location failed, please try again!:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
            }
        }
    };

    private void refreshTvAddress() {
        if (null != lastDBLocation) {
            tvAddress.setText(LocationManager.getDetailAddr(lastDBLocation,
                    false));
        } else {
            if ("en".equals(mEns)) {
                tvAddress.setText("Is positioning.....");
            } else {
                tvAddress.setText("正在定位.....");
            }

        }
    }

}
